package com.cy.store.controller;

import com.cy.store.entity.Address;
import com.cy.store.service.IAddressService;
import com.cy.store.service.IUserService;
import com.cy.store.service.ex.UpdateException;
import com.cy.store.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/address")
public class AddressController extends BaseController {
    @Autowired
    private IAddressService addressService;

    @RequestMapping("/add_new_address")
    public JsonResult<Void> addNewAddress(HttpSession session, Address address){
        Integer uid = getUidFromSession(session);
        String username = getUsernameFromSession(session);
        //调用业务方法
        addressService.addNewAddress(uid,username,address);
        return new JsonResult<>(OK);
    }


    @GetMapping({"", "/"})
    public JsonResult<List<Address>> getByUid(HttpSession session) {
        Integer uid = getUidFromSession(session);
        List<Address> data = addressService.getByUid(uid);
        return new JsonResult<>(OK, data);
    }

    @RequestMapping("{aid}/set_default")
    public JsonResult<Void> setDefault(@PathVariable("aid") Integer aid,HttpSession session){

        addressService.setDefault(aid,getUidFromSession(session),getUsernameFromSession(session));
        return new JsonResult<>(OK);

    }

    @RequestMapping("{aid}/delete")
    public JsonResult<Void> deleteAddress(@PathVariable("aid") Integer aid,HttpSession session){
        Integer uid = getUidFromSession(session);
        String username = getUsernameFromSession(session);
        addressService.deleteAddressByAid(aid,uid,username);
        return new JsonResult<>(OK);

    }

    /**
     * Description : 处理查询某个指定aid地址的请求
     * @date 2022/7/15
     * @param aid 地址aid
     * @return top.year21.computerstore.utils.JsonResult<top.year21.computerstore.entity.Address>
     **/
    @GetMapping("/queryOneAddress")
    public JsonResult<Address> queryOneAddress(Integer aid){
        Address address = addressService.queryAddressByAid(aid);
        //过滤部分不需要的字段
        address.setModifiedTime(null);
        address.setModifiedUser(null);
        address.setCreatedTime(null);
        address.setCreatedUser(null);

        return new JsonResult<>(OK,address);
    }

    @PostMapping("/updateAddress")
    public JsonResult<Void> updateOneAddress(Address address,HttpSession session){
        //取出session中用户名
        String modifiedUser = getUsernameFromSession(session);
        int result = addressService.updateOneAddress(address, modifiedUser);
        if (result == 0){
            throw new UpdateException("修改地址时，服务器或数据库异常");
        }
        return new JsonResult<>(OK);
    }



}
